#include "PlayHavenHelper.h"
#include "cocos2d.h"

USING_NS_CC;

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)

#include "platform/android/jni/JniHelper.h"
#include <jni.h>

#ifdef __cplusplus
extern "C" {
#endif

JNIEXPORT void JNICALL Java_com_mangoqueen_game_BearBabyDaily_PlayHavenHelper_initJNI(JNIEnv*, jobject, jobject);

#ifdef __cplusplus
}
#endif

static jmethodID mid;
static jclass mClass;
static jobject mObject;

JNIEXPORT void JNICALL Java_com_mangoqueen_game_BearBabyDaily_PlayHavenHelper_initJNI(JNIEnv* env, jobject thiz, jobject weak_this)
{
	jclass clazz = env->GetObjectClass(thiz);
	mClass = (jclass)env->NewGlobalRef(clazz);
	mObject = env->NewGlobalRef(weak_this);
}

class PlayHavenHelperEnv
{
public:
    PlayHavenHelperEnv()
    {
        m_isAttached = false;
	    int status = JniHelper::getJavaVM()->GetEnv((void**)&m_env, JNI_VERSION_1_6);
	    if (status < 0)
	    {
		    CCLOG("AdMobHelperEnv: JavaVM::GetEnv failed, assuming native thread");
		    status = JniHelper::getJavaVM()->AttachCurrentThread(&m_env, NULL);
		    if (status < 0)
		    {
			    CCLOG("AdMobHelperEnv: failed to attach current thread");
			    return;
		    }
		    m_isAttached = true;
	    }
        return;
    }

    ~PlayHavenHelperEnv()
    {
        if (m_isAttached) JniHelper::getJavaVM()->DetachCurrentThread();
    }

    JNIEnv* operator-> () { return m_env; }

protected:
    bool m_isAttached;
    JNIEnv* m_env;
};

static void PlayHavenHelper_startList(const string & tag)
{
    PlayHavenHelperEnv env;
	mid = env->GetStaticMethodID(mClass, "nativeStartList", "(Ljava/lang/String;)V");
    jstring jTag = env->NewStringUTF(tag.c_str());
	if (mid != NULL) env->CallStaticVoidMethod(mClass, mid, jTag);
}

#endif

PlayHavenHelper::PlayHavenHelper()
{
}

PlayHavenHelper::~PlayHavenHelper()
{
}

PlayHavenHelper * PlayHavenHelper::getInstance()
{
  static PlayHavenHelper helper;
  return &helper;
}

void PlayHavenHelper::startList(const string & tag)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
  PlayHavenHelper_startList(tag);
#endif
}
